/*
 * @Author: your name
 * @Date: 2021-02-22 15:42:16
 * @LastEditTime: 2021-03-08 21:51:09
 * @LastEditors: Please set LastEditors
 * @Description: 各种函数/方法手写
 * @FilePath: \relearnJS\interview\手写方法.js
 */
//? trim
const trim_test = `    abc  po `
//* 1. 
String.prototype.myTrim1 = function () {
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
}

//* 2.
String.prototype.myTrim2 = function () {
    return this.substring(Math.max(this.search(/\S/), 0), this.search(/\S\s*$/) + 1)
}

//* 3. 
String.prototype.myTrim3 = function () {
    var str = this
    whitespace = ` \n\t\r`
    for (var i = 0, len = str.length; i < len; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i)
            break
        }
    }
    for (i = str.length - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1)
            break
        }
    }
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : ''
}
console.log(trim_test.myTrim1())
console.log(trim_test.myTrim2())
console.log(trim_test.myTrim3())

//? indexOf
//* 正则匹配
String.prototype.myIndexOf = function (searchStr, fromIndex = 0) {
    var regex = new RegExp(`${searchStr}`, 'ig')
    regex.lastIndex = fromIndex
    var result = regex.exec(this)
    return result ? result.index : -1
}

Array.prototype.myIndexOf = function (elem, fromIndex = 0) {
    if (!elem) return -1
    for (var i = fromIndex, len = this.length; i < len; i++) {
        if (this[i] === elem) return i
    }
    return -1
}

var str = 'abcdeabc',
    arr = ['abcd', 'abc', 'abcdeabc', 'fa']
console.log(str.myIndexOf('abc'))
console.log(arr.myIndexOf('abc'))